package com.crm.business.crm.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.crm.business.admin.service.AdminService;
import com.crm.business.crm.mapper.CrmHeadquartersBusinessBalanceMapper;
import com.crm.business.crm.mapper.CrmHeadquartersBusinessMapper;
import com.crm.business.crm.service.CrmPageService;
import com.crm.business.crm.service.ICrmHeadquartersBusinessBalanceService;
import com.crm.business.crm.service.ICrmHeadquartersBusinessService;
import com.crm.business.utils.ActionRecordUtil;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.constant.FieldEnum;
import com.crm.common.crm.entity.BO.CrmModelSaveBO;
import com.crm.common.crm.entity.BO.CrmRoiSearchBO;
import com.crm.common.crm.entity.BO.CrmUpdateInformationBO;
import com.crm.common.crm.entity.PO.CrmHeadquartersBusiness;
import com.crm.common.crm.entity.PO.CrmHeadquartersBusinessBalance;
import com.crm.common.crm.entity.VO.CrmFieldSortVO;
import com.crm.common.crm.entity.VO.CrmModelFiledVO;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.business.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CrmHeadquartersBusinessServiceImpl extends BaseServiceImpl<CrmHeadquartersBusinessMapper, CrmHeadquartersBusiness> implements ICrmHeadquartersBusinessService, CrmPageService {


    @Autowired
    private ICrmHeadquartersBusinessBalanceService CrmHeadquartersBusinessBalanceService;

    @Autowired
    private CrmHeadquartersBusinessBalanceMapper crmHeadquartersBusinessBalanceMapper;

    @Autowired
    private AdminService adminService;

    @Autowired
    private ActionRecordUtil actionRecordUtil;

    @Override
    public String[] appendSearch() {
        return new String[0];
    }

    @Override
    public void setOtherField(Map<String, Object> map) {

    }

    @Override
    public CrmEnum getLabel() {
        return null;
    }

    @Override
    public CrmHeadquartersBusiness queryBySource(String topUpSource) {
        return getBaseMapper().queryBySource(topUpSource);
    }
    @Override
    public CrmHeadquartersBusiness queryById(Integer id) {
        return getBaseMapper().queryById(id);
    }
    @Override
    public void deleteByIds(CrmHeadquartersBusiness crmHeadquartersBusiness) {
        removeById( crmHeadquartersBusiness.getId());
    }

    /**
     * 列表查询
     * @param search
     * @return
     */
    @Override
    public BasePage<CrmHeadquartersBusiness> queryPageList(CrmRoiSearchBO search) {
        Integer pageStart = search.getPage() > 0 ? (search.getPage() - 1) * search.getLimit() : 0;
        search.setPageStart(pageStart);

        List<CrmHeadquartersBusiness> crmHeadquartersBusinessList = getBaseMapper().queryPageList(search);
        BasePage<CrmHeadquartersBusiness> basePage = new BasePage<>(search.getPage(),search.getLimit(),crmHeadquartersBusinessList.size());
        basePage.setList(crmHeadquartersBusinessList);
        Integer total = getBaseMapper().queryRow();
        basePage.setTotal(total);
        return basePage;
    }


    @Override
    public void addOrUpdate(CrmModelSaveBO crmModel) {
        //List<String> sourceList = getBaseMapper().querySource();

        CrmHeadquartersBusiness crmHeadquartersBusiness = BeanUtil.copyProperties(crmModel.getEntity(),CrmHeadquartersBusiness.class);

            if (crmHeadquartersBusiness.getId() != null) {
                // 编辑
                CrmHeadquartersBusiness oldCrmHeadquartersBusiness = this.queryById(crmHeadquartersBusiness.getId());

                crmHeadquartersBusiness.setUpdateTime(new Date());
                crmHeadquartersBusiness.setUpdateUserId(UserUtil.getUserId());

                actionRecordUtil.updateRecord(BeanUtil.beanToMap(this.queryById(crmHeadquartersBusiness.getId())), BeanUtil.beanToMap(crmHeadquartersBusiness), CrmEnum.ALLIANCE_BUSINESS, String.valueOf(crmHeadquartersBusiness.getId()), crmHeadquartersBusiness.getId());

                updateById(crmHeadquartersBusiness);
                //更新充值后：余额-旧充值+新充值
                CrmHeadquartersBusinessBalance crmHeadquartersBusinessBalance = this.crmHeadquartersBusinessBalanceMapper.queryDataBySource(crmHeadquartersBusiness.getTopUpSource(),crmHeadquartersBusiness.getDeptId());
                crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusinessBalance.getBalance().subtract(oldCrmHeadquartersBusiness.getTopUpPrice()).add(crmHeadquartersBusiness.getTopUpPrice()));
                this.CrmHeadquartersBusinessBalanceService.updateById(crmHeadquartersBusinessBalance);
            } else {
                // 新增
                //if (sourceList.contains(crmHeadquartersBusiness.getTopUpSource())){
                 //   throw new CrmException(CrmCodeEnum.CRM_HEADQUARTERS);
               // }
                crmHeadquartersBusiness.setCreateTime(new Date());
                crmHeadquartersBusiness.setCreateUserId(UserUtil.getUserId());
                save(crmHeadquartersBusiness);

                actionRecordUtil.addRecord(crmHeadquartersBusiness.getId(), CrmEnum.ALLIANCE_BUSINESS, String.valueOf(crmHeadquartersBusiness.getId()));

                //新建充值后更新余额表信息
                CrmHeadquartersBusinessBalance crmHeadquartersBusinessBalance = this.crmHeadquartersBusinessBalanceMapper.queryDataBySource(crmHeadquartersBusiness.getTopUpSource(),crmHeadquartersBusiness.getDeptId());
                if (crmHeadquartersBusinessBalance == null) {
                    crmHeadquartersBusinessBalance = new CrmHeadquartersBusinessBalance();
                    crmHeadquartersBusinessBalance.setDeptId(crmHeadquartersBusiness.getDeptId());
                    crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusiness.getTopUpPrice());
                    crmHeadquartersBusinessBalance.setTopUpSource(crmHeadquartersBusiness.getTopUpSource());
                    this.CrmHeadquartersBusinessBalanceService.save(crmHeadquartersBusinessBalance);
                } else {
                    crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusinessBalance.getBalance().add(crmHeadquartersBusiness.getTopUpPrice()));
                    this.CrmHeadquartersBusinessBalanceService.updateById(crmHeadquartersBusinessBalance);
                }
            }

    }

    @Override
    public void updateInformation(CrmUpdateInformationBO updateInformationBO) {

    }

    /**
     * 查询所有字段
     *
     * @return data
     */
    @Override
    public List<CrmModelFiledVO> queryField(Integer id) {
        return queryDefaultField();
    }

    /**
     * 下载导入模板
     *
     * @param response 线索id
     */
    @Override
    public void downloadExcel(HttpServletResponse response) throws IOException {

    }

    public List<CrmFieldSortVO> queryListHead(){
        List<CrmFieldSortVO> list = new ArrayList<>();
        list.add(new CrmFieldSortVO().setName("投放平台").setType(FieldEnum.SELECT.getType()).setFieldName("putinPlatform").setFormType(FieldEnum.SELECT.getFormType()));
        list.add(new CrmFieldSortVO().setName("大类").setType(FieldEnum.TEXT.getType()).setFieldName("category").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道充值金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道消耗金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("practicalPutinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道返点金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinRebatesMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道赔付金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinCompensateMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道转入金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("rollinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道转出金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("rolloutMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("备注").setType(FieldEnum.TEXT.getType()).setFieldName("remark").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("表单录入时间").setType(FieldEnum.DATE.getType()).setFieldName("putinFormDate").setFormType(FieldEnum.DATE.getFormType()));
        list.add(new CrmFieldSortVO().setName("创建时间").setType(FieldEnum.DATETIME.getType()).setFieldName("createTime").setFormType(FieldEnum.DATETIME.getFormType()));
        list.add(new CrmFieldSortVO().setName("创建人").setType(FieldEnum.TEXT.getType()).setFieldName("putinUserName").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("审核状态").setType(FieldEnum.TEXT.getType()).setFieldName("checkStatus").setFormType(FieldEnum.TEXT.getFormType()));

        return list;
    }

    public void exportExcel(HttpServletResponse response, CrmRoiSearchBO search){

    }

    /**
     * 查询所有字段
     *
     * @return data
     */
    @Override
    public List<CrmModelFiledVO> queryDefaultField() {
        //查询 线索 自定义字段 中 客户来源 作为 投放平台下拉选项
        List<CrmModelFiledVO> filedList = new ArrayList<>();
        //投放金额
        filedList.add(new CrmModelFiledVO("putinMoney", FieldEnum.FLOATNUMBER,"投放金额",1).setIsNull(1).setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        //实际投放金额
        filedList.add(new CrmModelFiledVO("practicalPutinMoney", FieldEnum.FLOATNUMBER,"实际投放金额",1).setIsNull(1).setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        //课程期数
        filedList.add(new CrmModelFiledVO("coursePeriods", FieldEnum.TEXT,"课程期数",1).setIsNull(1).setIsUnique(1).setFormType(FieldEnum.TEXT.getFormType()));
        //投放日期
        filedList.add(new CrmModelFiledVO("putinDate", FieldEnum.TEXT,"投放日期",1).setIsNull(1).setIsUnique(1).setFormType(FieldEnum.TEXT.getFormType()));
        return filedList;
    }

    public CrmHeadquartersBusiness getListById(Integer id){
        CrmHeadquartersBusiness CrmHeadquartersBusiness= baseMapper.queryListById(id);
        String batchIds=CrmHeadquartersBusiness.getBatchId();
        CrmHeadquartersBusiness.setFileList(baseMapper.queryListCrmBatch(batchIds));
        return CrmHeadquartersBusiness;
    }
}
